package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.format.DateUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import app.dinus.com.itemdecoration.GridDividerItemDecoration
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bytedance.applog.game.GameReportHelper
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.kwai.monitor.log.TurboAgent
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.DetailPicAdapter
import com.lykj.llw.box.data.bean.response.PayResponse
import com.lykj.llw.box.data.bean.response.SaleDetailDisplayResponse
import com.lykj.llw.box.data.entity.PayResult
import com.lykj.llw.box.databinding.ActRoleBuyDetailBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.json.JSONObject

/**
 * ================================================
 * 角色购买详情页
 * ================================================
 *
 * @author gosha
 * @date 2023/10/20-16:23
 */
class RoleBuyDetailActivity : BaseActivity() {
    lateinit var binding: ActRoleBuyDetailBinding

    private val mAdapter = DetailPicAdapter()
    private val mData = ArrayList<String>()
    var id = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActRoleBuyDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar
            .with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    override fun initUI() {
        id = intent.getIntExtra("id", 0)

        binding.titleBar.tvTitle.text = "商品详情"
        binding.titleBar.tvRightOption.visibility = View.GONE

        if (!BConstants.isDebug) {
            binding.tvBtnDownload.visibility = View.GONE
            binding.tvSmallAccountSort.visibility = View.GONE
//            binding.tvDesc1.visibility = View.GONE
//            binding.tvDesc2.visibility = View.GONE
        }

        initRCV()
    }

    private fun initRCV() {
        val gridLayoutManager = GridLayoutManager(this, 4)
        binding.rcvPic.layoutManager = gridLayoutManager
        binding.rcvPic.setHasFixedSize(true)

        val dividerItemDecoration = GridDividerItemDecoration(
            this,
            GridDividerItemDecoration.GRID_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setHorizontalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        dividerItemDecoration.setVerticalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        binding.rcvPic.addItemDecoration(dividerItemDecoration, 0)
        mAdapter.data = mData
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, ImageDisplayActivity::class.java)
            intent.putExtra("pic", mAdapter.getItem(position))
            startActivity(intent)
        }
        binding.rcvPic.adapter = mAdapter
    }

    //获取售卖详情
    private fun obtainSaleDetail() {
        RetrofitManager.instance.obtainSaleDetail(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@RoleBuyDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(
                    responseBody,
                    SaleDetailDisplayResponse::class.java
                )

                setUIAttr(bean.data)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@RoleBuyDetailActivity, msg)
                }
            }
        }, "$id")
    }

    //购买
    private fun buy(tranId: String) {
        RetrofitManager.instance.buy(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@RoleBuyDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                var bean = GsonUtils.fromJson(
                    responseBody, PayResponse::class.java
                )
                if (!bean.data.statusX) {
                    ToastUtils.showShort(this@RoleBuyDetailActivity, "${bean.data.messageX}")
                    return
                }
                alipay(bean.data.data)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@RoleBuyDetailActivity, msg)
                }
            }
        }, tranId)
    }

    private fun alipay(info: String) {
        Thread {
            val alipay = PayTask(this)
            val result = alipay.payV2(info, true)
            val payResult = PayResult(result)
            val resultInfo: String? = payResult.result // 同步返回需要验证的信息
            val resultStatus: String? = payResult.resultStatus
            LogUtils.e("asd", "alipay: $resultInfo::$resultStatus::$payResult")
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                runOnUiThread {
                    ToastUtils.showShort(this, "支付成功")

                    var jsonObj = JSONObject(resultInfo)
                    var money = jsonObj.getJSONObject("alipay_trade_app_pay_response").getDouble("total_amount").toInt()
                    LogUtils.e("$money")
                    GameReportHelper.onEventPurchase(
                        "",
                        "",
                        "",
                        1,
                        "支付宝",
                        "¥",
                        true,
                        money
                    )
                    LogUtils.e("---------巨量用户支付---已上报---------")

                    TurboAgent.onPay(money.toDouble())
                    LogUtils.e("---------快手用户支付---已上报---------")
                }
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                runOnUiThread {
                    ToastUtils.showShort(this, "支付失败")
                }
            }
        }.start()
    }

    private fun setUIAttr(data: SaleDetailDisplayResponse.DataDTO?) {
        binding.tvGameName.text = "${data?.gameName}"
        binding.tvChildName.text = "角色：${data?.rolename}"
        binding.tvPayMoney.text = "${data?.money}"
        binding.tvCustomAmount.text = "${data?.payMoney}"
        binding.tvServerZone.text = "${data?.zonename}"
        binding.tvDesc1.text = "${data?.userRemark}"

        if (data?.userRemark.isNullOrBlank()) {
            binding.tvDesc1.visibility = View.GONE
        } else {
            binding.tvDesc1.visibility = View.VISIBLE
        }
        binding.tvCreateDays.text =
            "${TimeUtils.getTimeSpanByNow(data?.roleCreateTime, TimeConstants.DAY) * -1}天"

        binding.tvOnSaleTime.text =
            "${TimeUtils.date2String(TimeUtils.string2Date(data?.createTime), "yyyy-MM-dd")}"

        GlideApp.with(this)
            .load(data?.gameIcon)
            .transition(DrawableTransitionOptions.withCrossFade())
            .into(binding.ivIcon)

        if (data?.picList?.isEmpty() != true) {
            mData.addAll(data?.picList!!)
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
        obtainSaleDetail()
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.tvBtnDownload.clickWithTrigger {
            ToastUtils.showShort(this, "点击了下载")
        }

        binding.tvBtnBuy.clickWithTrigger {
            buy("$id")
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}